class ArrayUtils {
  // 冒泡排序
  bubbleSort(arr: number[]) {
    if (arr.length <= 1) return arr
    for (let i = 0; i < arr.length - 1; i++) {
      for (let j = 0; j < arr.length - 1 - i; j++) {
        if (arr[j] > arr[j + 1]) {
          let num = arr[j]
          arr[j] = arr[j + 1]
          arr[j + 1] = num
        }
      }
    }
    return arr
  }
  // 快速排序
  quickSort(arr: number[]): number[] {
    if(arr.length <= 1) return arr
    let centerIndex = Math.floor(arr.length / 2)
    let center = arr[centerIndex]
    arr.splice(centerIndex, 1)
    let left = []
    let right = []
    for (let i = 0; i < arr.length; i++) {
      if(arr[i] < center) {
        left.push(arr[i])
      } else {
        right.push(arr[i])
      }
    }
    return this.quickSort(left).concat([center], this.quickSort(right))
  }

  // 插入排序
  insertSort(arr: number[]) {
    let current: number, preIndex: number
    for (let i = 0; i < arr.length; i++) {
      preIndex = i - 1
      current = arr[i]
      while (preIndex >= 0 && current < arr[preIndex]) {
        arr[preIndex + 1] = arr[preIndex]
        preIndex--
      }
      arr[preIndex + 1] = current
    }
    return arr
  }

  // 选择排序
  selectSort(arr: number[]) {
    let minIndex: number, temp: number
    for (let i = 0; i < arr.length - 1; i++) {
      minIndex = i
      for (let j = i + 1; j < arr.length; j++) {
        if(arr[j] < arr[minIndex]) {
          minIndex = j
        }
      }
      temp = arr[i]
      arr[i] = arr[minIndex]
      arr[minIndex] = temp
    }
    return arr
  }

  isArray(arr: any) {
    return Array.isArray(arr)
  }

  // 数组内容求和
  arraySum(arr: number[]) {
    let value = 0
    if(arr.length === 0) return 0
    arr.forEach(item => {
      value += Number(item)
    })
    return value
  }

  // 数组去重
  unique(arr: any[]) {
    return Array.from(new Set(arr))
  }
}

export default new ArrayUtils()